﻿using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Ninject;
using Tetris.Interfaces;

namespace Tetris.Screens
{
    public class GameplayScreen: GameScreen
    {
        private ILevelManager _levelManager;
        private IInputManager _inputManager;
        private IGameManager _gameManager;
        private ILevel _currentLevel;
        private Player _player;

        public GameplayScreen()
        {
            TransitioningInTime = TimeSpan.FromSeconds( 1.5 );
            TransitioningOutTime = TimeSpan.FromSeconds( 0.5 );
        }

        public override void Initialize( IGameManager gameManager )
        {
            _levelManager = gameManager.ServiceLocator.Get<ILevelManager>();
            _inputManager = gameManager.ServiceLocator.Get<IInputManager>();
            _gameManager = gameManager;

            _currentLevel = _levelManager.GetNextLevel();
            _currentLevel.Initialize( gameManager );


            _player = new Player( PlayerIndex.One );

            _player.Initialize( gameManager );

            // once the load has finished, we use ResetElapsedTime to tell the game's
            // timing mechanism that we have just finished a very long frame, and that
            // it should not try to catch up.
            gameManager.Game.ResetElapsedTime();
        }

        public override void Update( GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen )
        {
            base.Update( gameTime, otherScreenHasFocus, false );

            if( IsActive && _currentLevel != null )
            {
                _currentLevel.Update( _gameManager );
                _player.Update( _gameManager, _inputManager );
            }
        }

        public override void HandleInput( IInputManager inputManager )
        {
            if( IsActive && _currentLevel != null && _player != null )
            {
                _player.Update( _gameManager, inputManager );
            }
        }

        public override void Draw( SpriteBatch spriteBatch, IGameManager gameManager, GameTime gameTime )
        {
            _currentLevel.Draw( spriteBatch, gameManager, gameTime );
            _player.Draw( spriteBatch, gameManager, gameTime );
        }
    }
}
